package com.apes.fn.tms.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.tms.model.Vehicle;
import com.apes.fn.tms.repository.VehicleRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.data.domain.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("vehicleService")
public class VehicleService extends DomainService {
    @Autowired
    VehicleRepository vehicleRepository;

    public Vehicle create(SimpleRequest simpleRequest){
        Vehicle vehicle = simpleRequest.getO(Vehicle.class);
        checkDate(vehicle);
        return vehicleRepository.saveAndFlush(vehicle);
    }

    public void checkDate(Vehicle vehicle){
        Vehicle newVehicle = vehicleRepository.findByVehicleNumber(vehicle.getVehicleNumber());
        if (newVehicle!=null) throw new RuntimeException("车牌号已被使用");
    }

    public Vehicle update(SimpleRequest simpleRequest){
        Vehicle vehicle = simpleRequest.getO(Vehicle.class);
        checkDate(vehicle);
        return vehicleRepository.saveAndFlush(vehicle);
    }

    private String delete(SimpleRequest simpleRequest){
        Integer versions = simpleRequest.get("version");
        Vehicle vehicle = simpleRequest.getO(Vehicle.class);
        if (vehicle.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        vehicleRepository.delete(vehicle);
        return "删除成功";
    }

    /**
     * 查询所有未绑定的车辆
     * @param request
     * @return
     */
    public Page<Vehicle> findAllByNoIn(SimpleRequest request){
       return vehicleRepository.findAllByNoIn( PageRequest.of(request.get("page"), request.get("size")));
    }


    public Page<Vehicle> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return vehicleRepository.findAll(JpaDsl.toCriteria(filters),PageRequest.of(request.get("page"), request.get("size"),sort));

    }

}
